from typing import List, Tuple
from collections import namedtuple
import os
import time


PATH_TO_LOGGING_SCRAPER = os.path.abspath(
    'scraper_bitrix/scraper/logging_scraper.txt'
)

def add_message_to_list_of_parser_action(text: str) -> None:
    """ Добавляем сообщение в список действий парсера """

    action_id = int(time.time())

    with open(PATH_TO_LOGGING_SCRAPER, 'a') as file:
        text = f'{action_id} {text}\n'
        file.write(text)


def message_to_list_of_parsing_actions(message: str):
    def wrapper(function):
        def wrapper_inner(self, *args, **kwargs):
            add_message_to_list_of_parser_action(message)
            return function(self, *args, **kwargs)
        return wrapper_inner
    return wrapper


def get_all_parsing_actions() -> List[Tuple]:
    """ Получаем все действия парсинга """

    list_of_actions = []
    scraper_actions = namedtuple(
        'ScraperAction', ['id', 'text']
    )

    with open(PATH_TO_LOGGING_SCRAPER) as file:
        for line in file:
            id, text = line.split(' ', 1)
            action = scraper_actions(id, text)
            list_of_actions.append(action)

    return list_of_actions


def get_latest_parsing_action(
    last_action_id: str,
    last_action_text: str
) -> List[Tuple]:
    """ Последние действия парсинга """

    last_parsing_action = []
    last_action_id = int(last_action_id)
    all_parsing_actions = get_all_parsing_actions()

    for action in all_parsing_actions:
        action_id = int(action.id)
        is_latest_action = action_id > last_action_id

        if is_latest_action and action.text != last_action_text:
            last_parsing_action.append(action)

    return last_parsing_action


def clear_scraper_logging() -> None:
    """ Очищаем логирование парсера """

    with open(PATH_TO_LOGGING_SCRAPER, 'wb'):
        pass
